﻿using System;
using System.IO;

namespace Microsoft.WowAddonStudio.Project.Import
{
	/// <summary>
	/// Abstract base class of different addon items. (Folder, Ace)
	/// </summary>
	public abstract class AddonItem : IAddonItem
	{
		#region Private members

		private const string tocExtension = ".toc";
		private const string luaExtension = ".lua";
		private const string frameExtension = ".xml";

		private readonly string relativePath;
		private readonly FileType fileType;

		#endregion

		#region Lifecycle methods

		/// <summary>
		/// Creates an instance of <see cref="AddonItem"/>.
		/// <param name="relativePath">Location of addon item relative to location of import.</param>
		/// </summary>
		protected AddonItem(string relativePath)
		{
			if (string.IsNullOrEmpty(relativePath))
				throw new ArgumentNullException("relativePath", "Relative path should not be null.");

			this.relativePath = relativePath;
			fileType = GetFileType();
		}

		#endregion

		#region IAddonItem Members

		/// <summary>
		/// Gets the relative path to the addon item.
		/// </summary>
		public string RelativePath
		{
			get { return relativePath; }
		}

		/// <summary>
		/// Gets the file type.
		/// </summary>
		public FileType Type
		{
			get { return fileType; }
		}

		/// <summary>
		/// Gets the contents of the addon item as a stream.
		/// </summary>
		/// <returns>An instance of the <see cref="Stream"/> class.</returns>
		public abstract Stream GetStream();

		#endregion

		#region Private member functions

		/// <summary>
		/// Gets the type of the file.
		/// </summary>
		/// <returns></returns>
		private FileType GetFileType()
		{
			string extension = Path.GetExtension(relativePath);
			FileType result = FileType.None;

			if (0 == string.Compare(extension, tocExtension, StringComparison.OrdinalIgnoreCase))
				result = FileType.TableOfContents;
			else if (0 == string.Compare(extension, luaExtension, StringComparison.OrdinalIgnoreCase))
				result = FileType.Code;
			else if (0 == string.Compare(extension, frameExtension, StringComparison.OrdinalIgnoreCase))
				result = FileType.Frame;

			return result;
		}

		#endregion
	}
}